import { createAsyncThunk } from '@reduxjs/toolkit';
import auth from '@/api/auth';
import { setUser } from '../slices/authSlice';

// 异步获取用户信息
export const fetchUserInfo = createAsyncThunk(
  'auth/fetchUserInfo',
  async (_, { dispatch, rejectWithValue }) => {
    try {
      const response = await auth.userInfo();
      if (response.code === 200 && response.data) {
        dispatch(setUser(response.data));
        return response.data;
      } else {
        return rejectWithValue('获取用户信息失败');
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return rejectWithValue(error.message || '获取用户信息失败');
    }
  }
);

// 异步登录
export const loginAsync = createAsyncThunk(
  'auth/loginAsync',
  async (credentials, { dispatch, rejectWithValue }) => {
    try {
      const response = await auth.login(credentials);
      if (response.code === 200 && response.data) {
        // 登录成功后自动获取用户信息
        dispatch(fetchUserInfo());
        return response.data;
      } else {
        return rejectWithValue(response.message || '登录失败');
      }
    } catch (error) {
      console.error('登录失败:', error);
      return rejectWithValue(error.message || '登录失败');
    }
  }
);